//
//  HWDRegisterViewController.m
//  Demo
//
//  Created by 龚碧容 on 2017/9/18.
//  Copyright © 2017年 hwd. All rights reserved.
//

#import "QLMRegisterViewController.h"

#import "JPUSHService.h"

@interface QLMRegisterViewController (){
    dispatch_source_t _timer;
}
@property (nonatomic,strong)UIButton *verifyBtn;

@property (nonatomic,strong)UITextField *phoneTF;
@property (nonatomic,strong)UITextField *verifycodeTf;
@property (nonatomic,strong)UITextField *passportTf;
@property (nonatomic,strong)UITextField *repeatTf;

@end

@implementation QLMRegisterViewController

- (void)textFieldDidChange:(UITextField *)textField{
    if (textField == _phoneTF) {
        if (textField.text.length > 11) {
            UITextRange *markedRange = [textField markedTextRange];
            if (markedRange) {
                return;
            }
            NSRange range = [textField.text rangeOfComposedCharacterSequenceAtIndex:11];
            textField.text = [textField.text substringToIndex:range.location];
        }
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIView *backView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreen_width, 44*4)];
    backView.backgroundColor=[UIColor whiteColor];
    backView.userInteractionEnabled=YES;
    [self.view addSubview:backView];
    
    self.phoneTF=[self _creatTextField:CGRectMake(20, 7, 200, 30) placeStr:@"请输入手机号"];
    self.phoneTF.keyboardType=UIKeyboardTypeNumberPad;
    [backView addSubview:self.phoneTF];
    
    [self.phoneTF addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    
    self.verifycodeTf=[self _creatTextField:CGRectMake(20, 44+7, 200, 30) placeStr:@"请输入验证码"];
    self.verifycodeTf.keyboardType=UIKeyboardTypePhonePad;
    [backView addSubview:self.verifycodeTf];
    
    self.verifyBtn=[self _creatButton:CGRectMake(kScreen_width-100-20, 44+7, 100, 30) title:@"发送验证码" image:nil];
    [backView addSubview:self.verifyBtn];
    
    self.passportTf=[self _creatTextField:CGRectMake(20, 88+7, kScreen_width-40, 30) placeStr:nil];
    [backView addSubview:self.passportTf];
    
    NSString *mobileStr=nil;
    if(_isEditMobile){
        self.title=@"修改手机号";
        mobileStr=@"请输入新手机号";
        [backView setFrame:CGRectMake(0, 0, kScreen_width, 44*3)];
        
        [self.passportTf addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }else{
        self.title=@"找回密码";
        mobileStr=@"请输入至少6位字母和数字组合的密码";
        self.passportTf.secureTextEntry=YES;
        self.repeatTf=[self _creatTextField:CGRectMake(20, 44*3+7, 200, 30) placeStr:@"请重复输入密码"];
        self.repeatTf.secureTextEntry=YES;
        [backView addSubview:self.repeatTf];
    }
    self.passportTf.placeholder=mobileStr;
    
    for (int i=1; i<4; i++) {
        UIView *line1=[[UIView alloc] initWithFrame:CGRectMake(17, 44*i, kScreen_width-17, 0.5)];
        line1.backgroundColor=[UIColor lightGrayColor];
        [backView addSubview:line1];
    }
    
    UIButton *commitButton = [UIButton buttonWithType:UIButtonTypeCustom];
    commitButton.frame = CGRectMake(0, kScreen_height-40-IOS11_OR_LATER_SPACE(34)-QLM_StatusBarAndNavigationBarHeight, kScreen_width, 40);
    commitButton.titleLabel.font=[UIFont boldSystemFontOfSize:18];
    [commitButton setTitle:@"确定" forState:UIControlStateNormal];
    [commitButton setTitleColor: [UIColor whiteColor] forState:UIControlStateNormal];
    commitButton.backgroundColor=kButtonColor;
    [commitButton addTarget:self action:@selector(commitBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:commitButton];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.navigationController.navigationBarHidden=NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)commitBtnAction:(UIButton *)btn{
    [self.view endEditing:YES];
    
    if (![ClientTool isMobileValid:_phoneTF.text]) {
        ETToast(@"请输入正确的手机号码");
        return;
    }else if ([_verifycodeTf.text length]==0) {
        ETToast(@"请输入验证码");
        return;
    }else if ([_passportTf.text length]==0) {
        ETToast(@"请输入密码");
        return;
    }
    
    NSString *urlPath=nil;
    NSDictionary *tokenDic=[NSMutableDictionary dictionary];
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    if (_isEditMobile) {
        if (![ClientTool isMobileValid:_passportTf.text]) {
            ETToast(@"请输入正确的手机号码");
            return;
        }
        if ([_phoneTF.text isEqualToString:_passportTf.text]) {
            ETToast(@"旧手机号和新手机号不能相同");
            return;
        }
        [dic setObject:_phoneTF.text forKey:@"oldPhoneNumber"];
        [dic setObject:_passportTf.text forKey:@"newPhoneNumber"];
        urlPath=@"/rest/resetPhoneNumber";
        
        NSString *token=[[NSUserDefaults standardUserDefaults] objectForKey:kLoginToken];
        tokenDic=[NSDictionary dictionaryWithObjectsAndKeys:token,@"token", nil];
        
    }else{
        if ([_repeatTf.text length]==0) {
            ETToast(@"请重复输入密码");
            return;
        }
        if (![ClientTool judgePassWordLegal:_passportTf.text]) {
            ETToast(@"请输入至少6位字母和数字组合的密码");
            return;
        }
        if (![ClientTool judgePassWordLegal:_repeatTf.text]) {
            ETToast(@"请输入至少6位字母和数字组合的密码");
            return;
        }
        [dic setObject:[ClientTool md5:_passportTf.text] forKey:@"password"];
        [dic setObject:[ClientTool md5:_repeatTf.text] forKey:@"confirmPassword"];
        [dic setObject:_phoneTF.text forKey:@"phoneNumber"];
        
        urlPath=@"/rest/resetPassword";
    }

    [dic setObject:_verifycodeTf.text forKey:@"code"];
    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:urlPath withParamers:dic andBody:tokenDic
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            
                            ETToastWithDelay(@"恭喜您，修改成功", 1);
                            
                            [[NSNotificationCenter defaultCenter] postNotificationName:@"loginUpdateMainUI" object:nil userInfo:nil];
                            
                            [[UserManager sharedManager] loginOut];
                            [JPUSHService setAlias:nil completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                            } seq:0];
                            
                            [NSTimer scheduledTimerWithTimeInterval:1.5 target:self selector:@selector(delayShowHud) userInfo:nil repeats:NO];
                            
                        }else{
                            ETToast(responseObject[@"msg"]);
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                    }
     ];
}

- (void)delayShowHud{
    if (_isEditMobile) {
        [self.navigationController popToRootViewControllerAnimated:YES];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)verifyCodeBtnAction{
    [self.view endEditing:YES];
    if ([_phoneTF.text length]==0) {
        ETToast(@"请输入手机号");
        return;
    }
    
    __block NSInteger time = 119; //倒计时时间
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),1.0*NSEC_PER_SEC, 0); //每秒执行
    
    dispatch_source_set_event_handler(_timer, ^{
        
        if(time <= 0){ //倒计时结束，关闭
            
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮的样式
                [self.verifyBtn setTitle:@"重新发送" forState:UIControlStateNormal];
                [self.verifyBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
                self.verifyBtn.userInteractionEnabled = YES;
            });
            
        }else{
            
            int seconds = time % 120;
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置按钮显示读秒效果
                [self.verifyBtn setTitle:[NSString stringWithFormat:@"重新发送(%.2d)", seconds] forState:UIControlStateNormal];
                [self.verifyBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
                self.verifyBtn.userInteractionEnabled = NO;
            });
            time--;
        }
    });
    dispatch_resume(_timer);
    
    NSMutableDictionary *dic=[NSMutableDictionary dictionary];
    [dic setObject:_phoneTF.text forKey:@"phoneNumber"];

    [self.view makeToastActivity:CSToastPositionCenter];
    [ClientTool postUrlPath:@"/rest/smsCode" withParamers:dic andBody:nil
                    success:^(id responseObject){
                        [self.view hideToastActivity];
                        NSInteger code = [[responseObject objectForKey:@"flag"] integerValue];
                        if (code == 1) {
                            ETToast(responseObject[@"msg"]);
                        }else{
                            ETToast(responseObject[@"msg"]);
                            [self updateBtn];
                        }
                    }failure:^(NSError *error){
                        [self.view hideToastActivity];
                        ETToast(@"服务器连接失败");
                        [self updateBtn];
                    }
     ];
}

- (void)updateBtn{
    dispatch_source_cancel(_timer);
    dispatch_async(dispatch_get_main_queue(), ^{
        //设置按钮的样式
        [self.verifyBtn setTitle:@"发送验证码" forState:UIControlStateNormal];
        [self.verifyBtn setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
        self.verifyBtn.userInteractionEnabled = YES;
    });
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (UIButton *)_creatButton:(CGRect)aFrame title:(NSString *)aTitle image:(NSString *)imageName{
    UIButton *newButton = [UIButton buttonWithType:UIButtonTypeCustom];
    newButton.frame = aFrame;
    newButton.titleLabel.font=[UIFont systemFontOfSize:14];
    [newButton setTitle:aTitle forState:UIControlStateNormal];
    [newButton setTitleColor:kButtonColor forState:UIControlStateNormal];
    [newButton addTarget:self action:@selector(verifyCodeBtnAction) forControlEvents:UIControlEventTouchUpInside];
    return newButton;
}

- (UITextField *)_creatTextField:(CGRect)aFrame placeStr:(NSString *)placeStr{
    UITextField *_textField=[[UITextField alloc] initWithFrame:aFrame];
    _textField.backgroundColor=[UIColor clearColor];
    _textField.placeholder=placeStr;
    _textField.font=[UIFont systemFontOfSize:16.0f];
    _textField.textColor=[UIColor darkGrayColor];
    _textField.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
    return _textField;
}

@end
